<!-- 导出Word文档 -->
<template>
  <div>
    <el-button type="primary" @click="exportWord">导出Word</el-button>
  </div>
  <div ref="wordContent">
    <div style="text-align: center; font-size: 48px; font-weight: bold; font-family: '宋体'">导出Word文档</div>
    <p>这是导出的Word文档内容</p>
    <img src="/logo.png" alt="图片" style="display: block; margin: 0 auto" />
  </div>
</template>

<script lang="ts" setup>
import { useTemplateRef } from 'vue'
import { saveAs } from 'file-saver'
import * as htmlDocx from 'html-docx-js-typescript'

const wordContent = useTemplateRef('wordContent')

const exportWord = async () => {
  if (!wordContent.value) {
    console.warn('无法获取到DOM元素')
    return
  }

  // 先处理图片，将其转换为 base64 编码
  const contentElement = wordContent.value.cloneNode(true) as HTMLElement
  const images = contentElement.querySelectorAll('img')

  // 处理每张图片
  for (let i = 0; i < images.length; i++) {
    const img = images[i] as HTMLImageElement
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')

    if (ctx) {
      // 创建临时图片对象用于获取宽高
      const tempImg = new Image()
      tempImg.crossOrigin = 'Anonymous'

      // 等待图片加载完成
      await new Promise<void>((resolve) => {
        tempImg.onload = () => {
          canvas.width = tempImg.width
          canvas.height = tempImg.height
          ctx.drawImage(tempImg, 0, 0)

          // 将图片转换为 base64 并替换原图片的 src
          img.src = canvas.toDataURL('image/png')
          resolve()
        }
        tempImg.onerror = () => {
          console.warn('图片加载失败:', img.src)
          resolve()
        }
        tempImg.src = img.src
      })
    }
  }

  // 使用 html-docx-js 转换为 DOCX
  const converted = await htmlDocx.asBlob(contentElement.innerHTML, {
    orientation: 'portrait',
    margins: { top: 720, right: 720, bottom: 720, left: 720 },
  })

  // 确保 converted 是 Blob 类型再传递给 saveAs
  if (converted instanceof Blob) {
    saveAs(converted, '导出文档.docx')
  } else {
    console.error('转换结果不是 Blob 类型')
  }
}
</script>
